/*
Copyright 2021 The Vitess Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package main

import (
	"fmt"
	"go/ast"
	"go/printer"
	gotoken "go/token"
	"go/types"
	"log"
	"os"
	"path"
	"slices"
	"strconv"
	"strings"

	"golang.org/x/tools/go/ast/astutil"
	"golang.org/x/tools/go/packages"

	"vitess.io/vitess/go/tools/codegen"
)

func main() {
	packageName := os.Args[1]

	config := &packages.Config{
		Mode: packages.NeedName |
			packages.NeedFiles |
			packages.NeedCompiledGoFiles |
			packages.NeedImports |
			packages.NeedTypes |
			packages.NeedSyntax |
			packages.NeedTypesInfo,
	}
	pkgs, err := packages.Load(config, packageName)
	if err != nil {
		log.Fatal("error loading package")
	}

	if err := codegen.CheckErrors(pkgs, codegen.GeneratedInSqlparser); err != nil {
		log.Fatal(err)
	}

	idx := slices.IndexFunc(pkgs, func(p *packages.Package) bool { return p.Name == "sqlparser" })
	if idx < 0 {
		log.Fatal("did not find package 'sqlparser'")
	}

	rewriter, err := NewRewriter(pkgs[idx])
	if err != nil {
		log.Fatal(err)
	}

	err = rewriter.Rewrite()
	if err != nil {
		log.Fatal(err)
	}
}

type Rewriter struct {
	pkg     *packages.Package
	astExpr *types.Interface
	astfmt  int
}

var printerConfig = printer.Config{Mode: printer.UseSpaces | printer.TabIndent, Tabwidth: 8}

func NewRewriter(pkg *packages.Package) (*Rewriter, error) {
	scope := pkg.Types.Scope()
	exprT := scope.Lookup("Expr").(*types.TypeName)
	exprN := exprT.Type().(*types.Named).Underlying()

	astfmt := slices.IndexFunc(pkg.GoFiles, func(f string) bool { return path.Base(f) == "ast_format.go" })
	if astfmt < 0 {
		return nil, fmt.Errorf("package '%s' does not contain 'ast_format.go'", pkg.Name)
	}

	return &Rewriter{
		pkg:     pkg,
		astExpr: exprN.(*types.Interface),
		astfmt:  astfmt,
	}, nil
}

func (r *Rewriter) Rewrite() error {
	file := r.pkg.GoFiles[r.astfmt]
	syntax := r.pkg.Syntax[r.astfmt]

	// Add fmt import since %d is handled by calling fmt.Sprintf("%d",...)
	astutil.AddImport(r.pkg.Fset, syntax, "fmt")
	astutil.Apply(syntax, r.replaceAstfmtCalls, nil)

	dirname, _ := path.Split(file)
	f, err := os.Create(path.Join(dirname, "ast_format_fast.go"))
	if err != nil {
		return err
	}
	_, _ = fmt.Fprintf(f, "// Code generated by ASTFmtGen. DO NOT EDIT.\n")
	_ = printerConfig.Fprint(f, r.pkg.Fset, syntax)
	_ = f.Close()

	return codegen.GoImports(f.Name())
}

func (r *Rewriter) replaceAstfmtCalls(cursor *astutil.Cursor) bool {
	switch v := cursor.Node().(type) {
	case *ast.Comment:
		v.Text = strings.ReplaceAll(v.Text, " Format ", " FormatFast ")
	case *ast.FuncDecl:
		if v.Name.Name == "Format" {
			v.Name.Name = "FormatFast"
		}
	case *ast.ExprStmt:
		if call, ok := v.X.(*ast.CallExpr); ok {
			switch r.methodName(call) {
			case "astPrintf":
				return r.rewriteAstPrintf(cursor, call)
			case "literal":
				callexpr := call.Fun.(*ast.SelectorExpr)
				callexpr.Sel.Name = "WriteString"
				return true
			}
		}
	}
	return true
}

func (r *Rewriter) methodName(n *ast.CallExpr) string {
	if call, ok := n.Fun.(*ast.SelectorExpr); ok {
		id := call.Sel
		if id != nil && !r.pkg.TypesInfo.Types[id].IsType() {
			return id.Name
		}
	}
	return ""
}

func (r *Rewriter) rewriteLiteral(rcv ast.Expr, method string, arg ast.Expr) ast.Stmt {
	expr := &ast.CallExpr{
		Fun: &ast.SelectorExpr{
			X:   rcv,
			Sel: &ast.Ident{Name: method},
		},
		Args: []ast.Expr{arg},
	}
	return &ast.ExprStmt{X: expr}
}

func (r *Rewriter) rewriteAstPrintf(cursor *astutil.Cursor, expr *ast.CallExpr) bool {
	callexpr := expr.Fun.(*ast.SelectorExpr)
	lit := expr.Args[1].(*ast.BasicLit)
	format, err := strconv.Unquote(lit.Value)
	if err != nil {
		panic("bad literal argument")
	}

	end := len(format)
	fieldnum := 0
	for i := 0; i < end; {
		lasti := i
		for i < end && format[i] != '%' {
			i++
		}
		if i > lasti {
			var arg ast.Expr
			var method string
			var lit = format[lasti:i]

			if len(lit) == 1 {
				method = "WriteByte"
				arg = &ast.BasicLit{
					Kind:  gotoken.CHAR,
					Value: strconv.QuoteRune(rune(lit[0])),
				}
			} else {
				method = "WriteString"
				arg = &ast.BasicLit{
					Kind:  gotoken.STRING,
					Value: strconv.Quote(lit),
				}
			}

			cursor.InsertBefore(r.rewriteLiteral(callexpr.X, method, arg))
		}
		if i >= end {
			break
		}
		i++ // '%'
		if format[i] == '#' {
			i++
		}

		token := format[i]
		switch token {
		case 'c':
			cursor.InsertBefore(r.rewriteLiteral(callexpr.X, "WriteByte", expr.Args[2+fieldnum]))
		case 's':
			cursor.InsertBefore(r.rewriteLiteral(callexpr.X, "WriteString", expr.Args[2+fieldnum]))
		case 'l', 'r', 'v':
			leftExpr := expr.Args[0]
			leftExprT := r.pkg.TypesInfo.Types[leftExpr].Type

			rightExpr := expr.Args[2+fieldnum]
			rightExprT := r.pkg.TypesInfo.Types[rightExpr].Type

			var call ast.Expr
			if types.Implements(leftExprT, r.astExpr) && types.Implements(rightExprT, r.astExpr) {
				call = &ast.CallExpr{
					Fun: &ast.SelectorExpr{
						X:   callexpr.X,
						Sel: &ast.Ident{Name: "printExpr"},
					},
					Args: []ast.Expr{
						leftExpr,
						rightExpr,
						&ast.Ident{
							Name: strconv.FormatBool(token != 'r'),
						},
					},
				}
			} else {
				call = &ast.CallExpr{
					Fun: &ast.SelectorExpr{
						X:   rightExpr,
						Sel: &ast.Ident{Name: "FormatFast"},
					},
					Args: []ast.Expr{callexpr.X},
				}
			}
			cursor.InsertBefore(&ast.ExprStmt{X: call})
		case 'd':
			call := &ast.CallExpr{
				Fun:  &ast.Ident{Name: "fmt.Sprintf"},
				Args: []ast.Expr{&ast.BasicLit{Value: `"%d"`, Kind: gotoken.STRING}, expr.Args[2+fieldnum]},
			}
			cursor.InsertBefore(r.rewriteLiteral(callexpr.X, "WriteString", call))
		default:
			panic(fmt.Sprintf("unsupported escape %q", token))
		}
		fieldnum++
		i++
	}

	cursor.Delete()
	return true
}
